// 成果页
import './index.less';
import {Image, View} from "@tarojs/components";
import {useEffect, useState} from "react";
import {wxActions} from "../../utils/wxActions";
import {GLOBAL_IMAGE} from "../../constant/contant";
import {AchList, SearchBar, SearchCount, Stage, Track} from "../../components/achCmpt";
import {Api} from "../../api/api";
import Taro, {useDidShow, useReachBottom} from "@tarojs/taro";
import {Logo} from "../../components/userCenterCmpt";

const TRACK_ARR = [
    "全部", "集成电路", "工业母机", "新一代移动通信", "工业软件", "人工智能", "生物技术", "新能源", "新能源汽车", "新材料"
];
const TRACK_ARR_SUB = [
    "集成电路", "工业母机", "新一代移动通信", "工业软件", "人工智能", "生物技术", "新能源", "新能源汽车", "新材料"
];

export default function Ach(props) {
    const [achList, setAchList] = useState([]); // 成果列表
    const [searchText, setSearchText] = useState("");
    const [trackActiveList, setTrackActiveList] = useState([]);
    const [stageActiveList, setStageActiveList] = useState([]); // 阶段选中列表,对象数组
    const [listIt, setListIt] = useState([]); // 赛道字典
    const [stages, setStages] = useState([]); // 阶段字典
    const [searchTimeout, setSearchTimeout] = useState(null); // 搜索延时
    const [pageIndex, setPageIndex] = useState(1); // 页码
    const [total, setTotal] = useState(0); // 总数

    useEffect(() => {
        //const fieldId = wxActions.getCurrentPageParams("fieldId");
        const fieldId = undefined;
        fieldId ? setTrackActiveList([TRACK_ARR[fieldId]]) : setTrackActiveList([]);
        Api.getListIt().then(res => {
            setListIt(res);
            refreshAchList({
                pageSize: 10,
                pageNum: 1,
                proName: "",
                itIds: fieldId ? getSearchItIds({
                    listIt_: res,
                    trackActiveList_: fieldId ? [TRACK_ARR[fieldId]] : []
                }) : "",
                stages: ""
            });
        }).catch((err) => {
            wxActions.showTip(err.message);
        });
        Api.getStage().then(res => {
            setStages(res);
        }).catch((err) => {
            wxActions.showTip(err.message);
        });
        fieldId && wxActions.updateCurrentPageParams("fieldId", "");
    }, []);

    useDidShow(() => {
        //const fieldId = wxActions.getCurrentPageParams("fieldId");
        const fieldId = undefined;
        if (fieldId) {
            setTrackActiveList([TRACK_ARR[fieldId]]);
            Api.getListIt().then(res => {
                setListIt(res);
                refreshAchList({
                    pageSize: 10,
                    pageNum: 1,
                    proName: "",
                    itIds: fieldId ? getSearchItIds({
                        listIt_: res,
                        trackActiveList_: fieldId ? [TRACK_ARR[fieldId]] : []
                    }) : "",
                    stages: ""
                });
            }).catch((err) => {
                wxActions.showTip(err.message);
            });
            Api.getStage().then(res => {
                setStages(res);
            }).catch((err) => {
                wxActions.showTip(err.message);
            });
            fieldId && wxActions.updateCurrentPageParams("fieldId", "");
        }
    });

     // 根据字典将trackActiveList转换为itId列表，英文逗号分隔
    function getSearchItIds({listIt_ = listIt, trackActiveList_ = trackActiveList}) {
        // 字典格式{"itId": "A1Jp4QOXoM",  "itName": "集成电路"}
        const itIds = listIt_.filter(item => trackActiveList_.indexOf(item.itName) !== -1).map(item => item.itId);
        return itIds.join(",");
    }

    function getSearchStageIds({stageActiveList_ = stageActiveList}) {
        const stageIds = stageActiveList_.map(item => item.stage);
        return stageIds.join(",");
    }

    // 搜索事件
    const handleSearch = (e) => {
        onSearchChange(e.target.value);
    }

    // 搜索框文本改变事件
    const onSearchChange = (value) => {
        setSearchText(value);
        // Clear the previous timeout if there was one
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }

         // Set a new timeout to execute the function after 2 seconds
        setSearchTimeout(setTimeout(() => {
            refreshAchList({
                pageSize: 10,
                pageNum: 1,
                proName: value,
                itIds: getSearchItIds({}),
                stages: getSearchStageIds({})
            });
        }, 2000));
    }

    // 请求成果列表
    const refreshAchList = (data) => {
        wxActions.showLoading('加载中');
        Api.getAchList(data).then(res => {
            setAchList(res.rows);
            setTotal(res.total);
            setPageIndex(1);
        }).finally(() => {
            Taro.hideLoading();
        });
    }

    // 赛道点击事件
    const trackClick = (text) => () => {
        let newTrackActiveList = [];
        if (trackActiveList.indexOf(text) !== -1) {
            newTrackActiveList = trackActiveList.filter(item => item !== text);
        } else {
            newTrackActiveList = [...trackActiveList, text];
        }
        setTrackActiveList(newTrackActiveList);
        refreshAchList({
            pageSize: 10,
            pageNum: 1,
            proName: searchText,
            itIds: getSearchItIds({trackActiveList_: newTrackActiveList}),
            stages: getSearchStageIds({})
        });
    }

    // 赛道全部点击事件
    const trackAllClick = () => {
        if (trackActiveList.length === 0) {
            return
        }
        setTrackActiveList([]);
        refreshAchList({
            pageSize: 10,
            pageNum: 1,
            proName: searchText,
            itIds: "",
            stages: getSearchStageIds({})
        });
    }

    // 判断stageActiveList是否包含stageObj
    const isStageActive = (stageObj) => {
        return stageActiveList.findIndex((item) => {
            return item.id === stageObj.id
        }) !== -1
    }

    // 阶段点击事件
    const stageClick = (stageObj) => () => {
        let newArr = [];
        if (isStageActive(stageObj)) {
            newArr = stageActiveList.filter(item => item.id !== stageObj.id);
        } else {
            newArr = [...stageActiveList, stageObj];
        }
        setStageActiveList(newArr);
        refreshAchList({
            pageSize: 10,
            pageNum: 1,
            proName: searchText,
            itIds: getSearchItIds({}),
            stages: getSearchStageIds({stageActiveList_: newArr})
        });
    }

    // 阶段全部点击事件
    const stageAllClick = () => {
        if (stageActiveList.length === 0) {
            return
        }
        setStageActiveList([]);
        refreshAchList({
            pageSize: 10,
            pageNum: 1,
            proName: searchText,
            itIds: getSearchItIds({}),
            stages: ""
        });
    }

    // 下触底事件
    useReachBottom(() => {
        if (pageIndex * 10 >= total) {
            return;
        }
        wxActions.showLoading('加载中');
        Api.getAchList({
            pageSize: 10,
            pageNum: pageIndex + 1,
            proName: searchText,
            itIds: getSearchItIds({}),
            stages: getSearchStageIds({})
        }).then(res => {
            setAchList([...achList, ...res.rows]);
            setPageIndex(pageIndex + 1);
        }).finally(() => {
            Taro.hideLoading();
        });
    });

    return (
        <View className={"ach"}>
            <View className={"bg_top"}>
                <Image src={GLOBAL_IMAGE.ach_top}/>
                <View className={"logo_row"}>
                    <Logo imgUrl={GLOBAL_IMAGE.logo2}/>
                </View>
            </View>
            <View className={"searchBar_row"}>
                <SearchBar
                    searchText={searchText}
                    handleSearch={handleSearch}
                    onSearchChange={onSearchChange}
                />
            </View>
            <View className={"track_row_box"}>
                <Track
                    trackClick={trackClick}
                    trackAllClick={trackAllClick}
                    trackActiveList={trackActiveList}
                />
            </View>
            {
                stages.length > 1 &&
                <View className={"stage_row_box"}>
                    <Stage
                        stages={stages}
                        stageActiveList={stageActiveList}
                        stageClick={stageClick}
                        stageAllClick={stageAllClick}
                    />
                </View>
            }
            <View className={"count_row"}>
                <SearchCount count={total}/>
            </View>
            <View className={"achList_row"}>
                <AchList
                    achList={achList}
                />
            </View>
        </View>
    )
}
